package com.github_dididipapa.mall.product.exception;

import com.github_dididipapa.common.exception.BizCodeEnume;
import com.github_dididipapa.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
* 集中处理异常
* */
@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = "com.github_dididipapa.mall.product.controller")
/*
 * @RestControllerAdvice(basePackages = "com.github_dididipapa.mall.product.controller")
 * 等价于@ControllerAdvice + @ResponseBody
 * 扫描指定包下的所有Controller
 * */
//@RestControllerAdvice(basePackages = "com.github_dididipapa.mall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(value =  MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题:{},异常类型:{}", e.getMessage(), e.getClass());
        Map<String, String> erroMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((item) -> {
            // 获取到错误提示
            String message = item.getDefaultMessage();
            // 获取错误的属性名字
            String field = item.getField();
            erroMap.put(field, message);
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), "数据校验出现问题").put("data", erroMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("错误：", throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
